package net.bat.service.message;

import java.util.List;
import java.util.Map;

import net.bat.entity.IdEntity;
import net.bat.entity.Message;
import net.bat.filter.ExtReq;
import net.bat.repository.MessageDao;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springside.modules.persistence.DynamicSpecifications;
import org.springside.modules.persistence.SearchFilter;
import org.springside.modules.persistence.SearchFilter.Operator;

//Spring Bean的标识.
@Component
//类中所有public函数都纳入事务管理的标识.
@Transactional
public class MessageService {
	@Autowired
	private MessageDao messageDao;
	
	
	public Message getMessage(Long id) {
		return messageDao.findOne(id);
	}
	public void saveMessage(Message entity) {
		messageDao.save(entity);
	}
	public void deleteMessage(Long id) {
		messageDao.delete(id);
	}

	public List<Message> getAllMessage() {
		return (List<Message>) messageDao.findAll();
	}

	//Long userId, Map<String, Object> searchParams,
	public Page<Message> getMessage( Map<String, Object> searchParams, int pageNumber, int pageSize, String sortType){
		PageRequest pageRequest = buildPageRequest(pageNumber, pageSize, sortType);
		Map<String, SearchFilter> filters = SearchFilter.parse(searchParams);
		Specification<Message> spec = DynamicSpecifications.bySearchFilter(filters.values(), Message.class);

		Page<Message> r = messageDao.findAll(spec, pageRequest);
		return r;
	}

	
	
	
	public Page<Message> getMessageEntities(int page, int start, int limit, String filter, String sort, int jid)
			throws Exception {
		ExtReq parser = new ExtReq();
		Map<String, SearchFilter> mf = parser.parseFilter(filter);
		Sort ms = parser.parseSort(sort);
		if(jid!=0){
			mf.put("jid", new SearchFilter("jid", Operator.EQ, jid));
		}
		
		mf.put("pid", new SearchFilter("pid", Operator.EQ, 0));
		PageRequest pageRequest = new PageRequest(page - 1, limit, ms);
		Specification<Message> spec = DynamicSpecifications.bySearchFilter(mf.values(), Message.class);
		Page<Message> r = messageDao.findAll(spec, pageRequest);
		return r;
	}
	
	/**
	 * 创建分页请求.
	 */
	private PageRequest buildPageRequest(int pageNumber, int pagzSize, String sortType) {
		Sort sort = null;
		if ("auto".equals(sortType)) {
			sort = new Sort(Direction.DESC, "id");
		} else if ("title".equals(sortType)) {
			sort = new Sort(Direction.ASC, "title");
		}

		return new PageRequest(pageNumber - 1, pagzSize, sort);
	}
	 

}
